<template>
    <div class="add">
      <span><b>上传导学案/课件</b></span>
      <el-card class="box-card">        
        <el-form :model="state.form" :rules="state.rules" ref="formRef" label-width="80px">
          <el-form-item label="附件" prop="file"> 
            <UploadDocxPptxFile ref="uploadDocxFileRef" :limit="5" :action="state.uploadGuidePaperFileServer" :father_method="getFileUrl"></UploadDocxPptxFile>   
          </el-form-item>
          <el-form-item label="标题：" prop="title">
            <el-input style="width: 500px" v-model="state.form.title" placeholder="" clearable></el-input>
          </el-form-item>
          <el-form-item label="说明：" prop="remark">             
          <!-- 这里放富文本框 -->
          <WangEditor 
          id="remarkEditor"
            ref="remarkEditorRef"
            @getEditorContent="onEditorChange" 
            :father_method="appendImageFromEditor" 
          /> 
         
          </el-form-item>
          <el-dropdown @command="onSelectSubject">
              <span class="el-dropdown-link">
                <el-text type="warning">选择学科</el-text>
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="1">初中数学</el-dropdown-item>
                  <el-dropdown-item command="2">初中科学</el-dropdown-item>
                  <!-- <el-dropdown-item command="3">初中英语</el-dropdown-item> -->
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          <el-form-item label="知识点：" prop="knowledgepoint">
           
              <el-select v-model="state.form.knowledgepoint" placeholder="知识点"  size="small" class="m-2">
                <el-option
                  v-for="item in knowledgepointOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
          </el-form-item>
          <el-form-item label="类型：" prop="type">
            <el-select v-model="state.form.type" class="m-2" placeholder="类型" size="small">
              <el-option
                v-for="item in paperTypeOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>            
          </el-form-item>
          
          <el-form-item label="开放：" prop="open_level">
            <el-select v-model="state.form.open_level" class="m-2" placeholder="公开/私密" size="small">
              <el-option
                v-for="item in openLevelOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
              />
            </el-select>             
          </el-form-item> 
          <el-form-item label="来源：" prop="reference">
            <el-input style="width: 300px" v-model="state.form.reference" placeholder="" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitAddPaper">提交</el-button> 
          </el-form-item>
        </el-form>  
                
        
      </el-card>      
    </div>
</template>


<script setup>
import Editor from '@/components/TinymceEditor.vue';
import WangEditor from '@/components/WangEditor.vue'
import axios from '@/utils/axios'
import { ElMessage } from 'element-plus'
import { reactive, ref, toRefs, onMounted, watch, onBeforeMount, onUnmounted,computed, } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { localGet, uploadGuidePaperFileServer, convertQuestionFormat } from '@/utils'
import { useStore } from 'vuex'
import UploadDocxPptxFile from '@/components/UploadDocxPptxFile.vue';
import { ArrowDown } from '@element-plus/icons-vue'

const remarkEditorRef=ref(null)
const formRef=ref(null)
const editor = ref(null) // 富文本编辑器 ref
const router = useRouter()
const knowledgepointOption = reactive([])
const paperTypeOption = [
  {
    value : 1,
    label : '导学案',
  },
  {
    value : 2,
    label : '课件',
  },
]
const openLevelOption = [
  {
    value : 'public',
    label : '所有人可见',
  },
  {
    value : 'private',
    label : '仅自己可见',
  },
  {
    value : 'friend',
    label : '好友可见',
    disabled: true,
  },
]
const validateKnowledgepoint = (rule, value, callback) => {
  if (value<=0) {
    callback(new Error('没有选择知识点'))
  }else {
    callback()
  }
}
const state = reactive({
  subject: '1',
  UploadDocxPptxFile, // 上传图片的接口地址，单图上传
  uploadGuidePaperFileServer,
  token: localGet('token') || '', // 存在本地的 token
  pictures: "",
  form:{          //题目表单 
    title: "标题",         
    remark: "作品说明，比如适合年级、作品优缺点等等",
    open_level: 'public',
    online: false,
    knowledgepoint: -1,   
    file: "",
    type: 1,    
    reference: "",  
  },
  
  rules: { // 规则
    file: [
    {required: 'true', message: '请上传附件', trigger: ['change']}
    ],
    title: [
      {required: 'true', message: '请填写作品标题', trigger: ['change']}
    ],
    remark: [
      {required: 'true', message: '请填写作品说明', trigger: ['change']}
    ],
    knowledgepoint: [
      {required: 'true', message: '请选择知识点', trigger: ['change']},
      {validator: validateKnowledgepoint, trigger: 'blur'}
    ],   
    open_level: [
      { required: 'true', message: '请选择类型', trigger: ['change'] }
    ], 
    type: [
      { required: 'true', message: '请选择类型', trigger: ['change'] }
    ], 
  },
})

onMounted(() => {
  // getChoiceList() 
})
// 当富文本编辑器的内容发生变化
const onEditorChange = (array, html) => {
  state.form.remark=html
  console.log('说明',state.form.remark)
}
// 从富文本编辑器的上传图片，获得的图片写入封面
const appendImageFromEditor=(image)=>{
  ElMessage.warning('本页面暂不支持图片上传！')
   if(image!=''){
      console.log("编辑器上传图片成功",image)
   }
}// 选择学科后，记录在state中
const onSelectSubject=(command)=>{
  state.subject=parseInt(command)
  console.log("选择学科", state.subject)
  getChoiceList()
}
// 初始化表单
const initQuestion=()=>{
  state.form={          //题目表单  
    title: "标题",         
    remark: "作品说明，比如适合年级、作品优缺点等等",
    open_level: 'public',
    online: false,
    knowledgepoint: -1,
    file: "",
    type: 1,    
    reference: "原创", 
  }
}

// 提交表单
const submitAddPaper = () => {
  state.form.remark = remarkEditorRef.value.getHtmlContent()
  console.log("我要提交表单啦：",state.form)
  formRef.value.validate((vaild, obj) => {
    if (vaild) {      
      let params = state.form
      axios.post('/GuidePaperModelViewSet/', params).then((result) => {
        if(result.code==200){
          ElMessage.success( '上传成功，并创建了申请上线！')
          var r=confirm("上传成功。现在就去查看？");
            if (r==true){
                router.push("/userCenter/myCreateGuidePaper")
            }else{
              initQuestion()
            }
        }else
        if(result.code==201){
          ElMessage.success( '上传成功，创建了申请上线失败！')
          var r=confirm("上传成功。现在去查看？");
            if (r==true){
                router.push("/userCenter/myCreateGuidePaper")
            }else{
              initQuestion()
            }
        }else
        {
          ElMessage.success( '失败！')
          console.log("提交错误", result.message)
        }       
      })
    }else{
      ElMessage.success( '表单没有通过！')      
      for (let key in obj) {
        console.log("具体原因是：", obj[key][0].message)
        return false;
      }   
    }
  })
}
// 从后台读取知识点列表
const getChoiceList =()=>{
  let params={
    subject_id:state.subject

  }
  console.log('发送知识点参数：',state.subject)
  axios.get(`/knowledgepoints/get_knowledge_by_subject`,{params}).then(res =>{
    console.log('获取知识点,',res)
    if (res.code == 200){
      const temp_list = res.data.results
      knowledgepointOption.splice(0)
      for (let i=0; i<temp_list.length; i++){
        knowledgepointOption.push({value:temp_list[i].id, label:temp_list[i].name})
      } 
    }else{
      console.log("error：", res)
    }
  }).catch((error)=>{
      console.log("发送错误：", error)
  })  
}
// 子组件upload返回过来的数据
const getFileUrl=(url)=>{    
    console.log("upload子组件传过来的",url)    
    ElMessage.success("文件上传成功！")
    state.form.file=url
    console.log("附件url关联到file：", state.form.file)
  } 

</script>


<style scoped>
  .add{
    width: 1000px;
  }
  .form{
    width: 900px;
  }
  .box-card{
    width: 950px;
  }
  .example-showcase .el-dropdown-link {
  cursor: pointer;
  color:blue;
  display: flex;
  align-items: center;
}
</style>